package bidsanity

import grails.converters.JSON

class BidController {
    def bidService
    def jmsService

    def index() {
        [bidInstanceList: Bid.list(sort: "listing"), bidInstanceTotal: Bid.count()]
    }

    def create() {
        [bidInstance: new Bid(params)]
    }

    def save() {
        def bid = [:]
        bid["status"] = true

        if (session.user){
                       
            def user = Customer.findByEmailAddress(session.user)
            
            if(params.amount == null || !params.amount.isDouble())  {
                bid["message"] = message(code: 'bid.was.not.valid', args: [])
                bid["status"] = false
            }
            else {
                def listingInstance = Listing.get(params.listingId)

                if (listingInstance.seller == user) {
                    bid["message"] = message(code: 'bid.sameperson', args: [bidInstance.bidder.getNameFromEMail()])
                    bid["status"] = false
                }
                else{
                    params.bidderId = user.id
                    def bidInstance = bidService.createBid(params)
                    if(!bidInstance){
                        bid["message"] = message(code: 'bid.listing.expired')
                        bid["status"] = false
                    }
                    else if (!listingInstance.save(failOnError: false, validate: true, flush: true)) {
                        bid["message"] = message(code: 'bid.bid.too.low', args: [String.format('$%.2f', bidInstance.amount)])
                        bid["status"] = false
                    }
                    else {
                        bid["bidder"] = user.getNameFromEMail()
                        bid["time"] = bidInstance.bidTime.time
                        bid["amount"] = String.format('$%.2f',bidInstance.amount)
                        bid["newMinimum"] = String.format('$%.2f',listingInstance.minimumBid)
                        bid["message"] = message(code: 'bid.was.registered', args: [bid["amount"]])
                    }
                }
            }
        }
        else {
            bid["message"] = message(code: 'bid.not.logged.in')
            bid["status"] = false
        }

        render bid as JSON

    }
}
